package com.wms.ymcc.mq;

import com.alibaba.fastjson.JSONObject;
import com.wms.ymcc.constant.ValidationConstants;
import com.wms.ymcc.domain.MessageStation;
import com.wms.ymcc.dto.MessageStationDto;
import com.wms.ymcc.exception.GlobalBaseException;
import com.wms.ymcc.service.IMessageStationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Date;

/**
 * @author : 阿盛哟
 * @description :
 * @createDate : 2025/6/20 20:28
 */
@RocketMQMessageListener(topic = ValidationConstants.ROCKETMQ_TOPIC_PUBLISH,
        selectorExpression = ValidationConstants.ROCKETMQ_TAGS_STATION,
        consumerGroup = "service-common-consumer-station")
@Service
@Slf4j
public class MQConsumerStationService implements RocketMQListener<MessageExt> {


    @Autowired
    private IMessageStationService messageStationService;

    /**
     * 消费
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1. 获取到消息
        try {
            String jsonStrMessage = new String(messageExt.getBody(), "UTF-8");
            MessageStationDto messageStationDto = JSONObject.parseObject(jsonStrMessage, MessageStationDto.class);
            // 2. 存到 t_message_station
            List<Long> ids = messageStationDto.getIds();

            ids.stream().forEach(id -> {
                MessageStation messageStation = new MessageStation();
                BeanUtils.copyProperties(messageStationDto,messageStation);
                messageStation.setUserId(id);
                messageStation.setSendTime(new Date());
                messageStation.setIsread(0);
                messageStationService.insert(messageStation);
            });

            log.info("站内推送消息消费结果成功");
        } catch (UnsupportedEncodingException e) {
            throw new GlobalBaseException("站内推送消息消费失败");
        }


    }
}